package org.infinity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class Config {
    private static final Log log = LogFactory.getLog(Config.class);

    private static Config config;

    private static final String DEST_PATH = "destPath";

    private static final String FREQUENCY = "frequency";

    private static final String CONFIG_FILE = "Config.properties";

    synchronized static Config getInstance() {
        if (config == null) {
            config = new Config();
        }
        return config;
    }

    private Config() {
        log.debug("initial Config   start");
        String destPath = props.getString(DEST_PATH);
//        if(!Util.checkPath(destPath)){
//            return;
//        }
        this.destPath = new File(destPath);
        frequency = 1000 * Long.valueOf(props.getString(FREQUENCY));
        log.debug("initial Config   end");
    }

    private String fixPath(String string) {
        return string;
    }

    private static ResourceBundle props = ResourceBundle.getBundle("Config");

    private long frequency;

    private File destPath;

    public long getFrequency() {
        return frequency;
    }

    public void setFrequency(long frequency) {
        log.debug("setFrequency:" + frequency);
        this.frequency = frequency;
        put(FREQUENCY, String.valueOf(frequency));
    }

    /**
     * @return
     */
    public File getDestPath() {
        return destPath;
    }

    /**
     * @param destPath
     */
    public void setDestPath(File destPath) {
        log.debug("setDistPath:" + destPath);
        this.destPath = destPath;
        put(DEST_PATH, destPath.getAbsolutePath());
    }

    /**
     * save properties
     * @param key
     * @param value
     */
    private void put(String key, String value) {
        Properties prop = new Properties();
        try {
            InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(
                    CONFIG_FILE);
            prop.load(in);
            prop.put(key, value);
            prop.store(new FileOutputStream(this.getClass().getClassLoader().getResource(
                    CONFIG_FILE).getFile()), "File monitor config");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
